package com.ibm.cloud.redis.connection;

import java.io.Closeable;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import io.lettuce.core.ReadFrom;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.codec.StringCodec;
import io.lettuce.core.masterreplica.MasterReplica;
import io.lettuce.core.masterreplica.StatefulRedisMasterReplicaConnection;

public class RedisSentinelGroupConnectionFactory implements Closeable {
	private Map<String, StatefulRedisConnection<String, String>> groupConnMap = new HashMap<>();
	/**
	 * Redis 连接模板，格式：
	 * redis-sentinel://[password@]host[:port][,host2[:port2]][/databaseNumber]#{groupKey}
	 */
	private String sentinelNodes = "192.168.99.2:27000,192.168.99.2:27001,192.168.99.2:27002";

	public String getSentinelNodes(String groupKey) {
		// TODO: 从数据库配置参数中获取哨兵配置
		return sentinelNodes;
	}

	public StatefulRedisConnection<String, String> getConnection(String groupKey) throws Exception {
		StatefulRedisConnection<String, String> conn = groupConnMap.get(groupKey);
		if (conn == null) {
			synchronized (this) {
				conn = groupConnMap.get(groupKey);
				if (conn == null) {
					RedisClient redisClient = RedisClient.create();
					StatefulRedisMasterReplicaConnection<String, String> connection = MasterReplica.connect(redisClient,
							StringCodec.UTF8,
							RedisURI.create("redis-sentinel://" + getSentinelNodes(groupKey) + "/0#" + groupKey));
					connection.setReadFrom(ReadFrom.REPLICA_PREFERRED);
					conn = connection;
					groupConnMap.put(groupKey, conn);
				}
			}
		}
		return conn;
	}

	@Override
	public void close() throws IOException {
		for (Entry<String, StatefulRedisConnection<String, String>> ent : groupConnMap.entrySet()) {
			ent.getValue().close();
		}
		groupConnMap.clear();
	}

}
